package com.dandandog.framework.faces.converter;

import cn.hutool.core.util.StrUtil;
import org.primefaces.util.LocaleUtils;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import java.util.Locale;

@FacesConverter("localeConverter")
public class LocaleConverter implements Converter<Locale> {
    @Override
    public Locale getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        if (StrUtil.isBlank(s)) {
            return null;
        }
        return LocaleUtils.toLocale(s);
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Locale locale) {
        if (locale == null) {
            return null;
        }
        return locale.getLanguage();
    }
}
